import requests
import time
from .config import VERIFY_CODE_API, REGISTER_API, INVITE_CODE
from .log import log_info, log_error, log_success, log_warning

SESSION = requests.Session()

# 检测官方邮箱发码平台是否正常
def check_send_code(email_to_test):
    """Checks if the target site's verification code sending API is responsive."""
    payload = {"email": email_to_test, "name": "", "type": "register"}
    log_info(f"检测目标网站发码API ({VERIFY_CODE_API}) using {email_to_test}")
    try:
        resp = SESSION.post(VERIFY_CODE_API, json=payload, timeout=10)
        # Check for successful status code AND expected response structure/value if possible
        if resp.status_code == 200:
            # Assuming 200 means success, might need adjustment based on actual API response
            try:
                data = resp.json()
                if data.get("code") == 200: # Check specific success code from API response
                     log_success("目标网站发码API检测成功")
                     return True
                else:
                    log_warning(f"目标网站发码API响应异常: code={data.get('code')}, msg={data.get('message')}")
                    return False
            except requests.exceptions.JSONDecodeError:
                 log_warning(f"目标网站发码API响应成功(200)，但无法解析JSON: {resp.text[:100]}")
                 return False # Treat non-JSON response as failure
        else:
            log_warning(f"目标网站发码API检测失败，状态码: {resp.status_code}, 响应: {resp.text[:100]}")
            return False
    except requests.exceptions.Timeout:
        log_error("目标网站发码API检测超时")
        return False
    except requests.exceptions.RequestException as e:
        log_error(f"目标网站发码API检测请求失败: {e}")
        return False
    except Exception as e:
        log_error(f"检测目标网站发码API时发生未知错误: {e}")
        return False

# 发送验证码给临时邮箱
def send_verification_code(email):
    """Requests the target site to send a verification code to the given email."""
    payload = {"email": email, "name": "", "type": "register"}
    log_info(f"请求向 {email} 发送验证码...")
    try:
        resp = SESSION.post(VERIFY_CODE_API, json=payload, timeout=10)
        if resp.status_code == 200:
             try:
                data = resp.json()
                if data.get("code") == 200:
                     log_success(f"成功请求向 {email} 发送验证码")
                     return True, None
                else:
                    err_msg = f"请求发送验证码API响应错误: code={data.get('code')}, msg={data.get('message')}"
                    log_error(err_msg)
                    return False, err_msg
             except requests.exceptions.JSONDecodeError:
                  err_msg = f"请求发送验证码响应成功(200)，但无法解析JSON: {resp.text[:100]}"
                  log_error(err_msg)
                  return False, err_msg
        else:
            err_msg = f"请求发送验证码失败，状态码: {resp.status_code}, 响应: {resp.text[:100]}"
            log_error(err_msg)
            return False, err_msg
    except requests.exceptions.Timeout:
        err_msg = "请求发送验证码超时"
        log_error(err_msg)
        return False, err_msg
    except requests.exceptions.RequestException as e:
        err_msg = f"请求发送验证码失败: {e}"
        log_error(err_msg)
        return False, err_msg
    except Exception as e:
        err_msg = f"请求发送验证码时发生未知错误: {e}"
        log_error(err_msg)
        return False, err_msg

# 注册用户功能
def register_user(username, password, code, email):
    """Registers the user on the target site."""
    payload = {
        "username": username,
        "password": password,
        "code": code,
        "email": email,
        "invite_code": INVITE_CODE
    }
    log_info(f"尝试使用邮箱 {email} 和用户名 {username} 在目标网站注册...")
    try:
        resp = SESSION.post(REGISTER_API, json=payload, timeout=15)
        if resp.status_code == 200:
             try:
                data = resp.json()
                if data.get("code") == 200:
                     log_success(f"用户 {username} ({email}) 在目标网站注册成功!")
                     return True, None # Success
                else:
                    err_msg = f"目标网站注册API响应错误: code={data.get('code')}, msg={data.get('message')}"
                    log_error(err_msg)
                    return False, err_msg # Registration failed according to API response
             except requests.exceptions.JSONDecodeError:
                  err_msg = f"目标网站注册响应成功(200)，但无法解析JSON: {resp.text[:100]}"
                  log_error(err_msg)
                  # Consider this a failure as we can't confirm success
                  return False, err_msg
        else:
            err_msg = f"目标网站注册请求失败，状态码: {resp.status_code}, 响应: {resp.text[:100]}"
            log_error(err_msg)
            return False, err_msg # HTTP error means failure
    except requests.exceptions.Timeout:
        err_msg = f"目标网站注册请求超时 for {username}"
        log_error(err_msg)
        return False, err_msg
    except requests.exceptions.RequestException as e:
        err_msg = f"目标网站注册请求失败 for {username}: {e}"
        log_error(err_msg)
        return False, err_msg
    except Exception as e:
        err_msg = f"目标网站注册时发生未知错误 for {username}: {e}"
        log_error(err_msg)
        return False, err_msg